﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Objects;
using System.Data;
using Condimar.Entities;

namespace Condimar.Repository
{
    public class ClienteJuridicoRepository:MasterRepository,IClienteJuridicoRepository
    {
        public List<ClienteJuridico> GetAllFromClienteJuridico()
        {
            var query = from c in context.ClienteJuridico.Include("Cliente")
                        select c;
            return query.ToList();
        }

        public List<ClienteJuridico> GetAllFromClienteJuridicoByCriterio(string criterio)
        {
            var query = from e in context.ClienteJuridico.Include("Cliente")
                        select e;
            if (criterio != null && criterio != string.Empty && criterio != "")
            {
                query = from e in context.ClienteJuridico.Include("Cliente")
                        where e.Ruc.Contains(criterio) ||
                                   e.RazonSocial.ToUpper().Contains(criterio)
                        select e;
            }
            return query.ToList();
        }

        public ClienteJuridico GetAllFromClienteJuridicoByRuc(string ruc)
        {
            var query = from c in context.ClienteJuridico.Include("Cliente")
                        where c.Ruc.CompareTo(ruc) == 0
                        select c;
            return query.SingleOrDefault();
        }

        public void AddClienteJiridico(ClienteJuridico cliJuridico)
        {
            cliJuridico.Cliente.Cliente_Juridico = null;
            cliJuridico.Cliente.Cliente_Natural = null;

            context.ClienteJuridico.Add(cliJuridico);
            context.SaveChanges();
        }

        public void UpdateClienteJuridico(ClienteJuridico cliJuridico)
        {
            var clienteJuridicoDB = (from c in context.ClienteJuridico.Include("Cliente")
                                    where c.Id.Equals(cliJuridico.Id)
                                    select c).SingleOrDefault();

            clienteJuridicoDB.Ruc = cliJuridico.Ruc;
            clienteJuridicoDB.RazonSocial = cliJuridico.RazonSocial;
            clienteJuridicoDB.Cliente.Direccion = cliJuridico.Cliente.Direccion;
            clienteJuridicoDB.Cliente.Telefono = cliJuridico.Cliente.Telefono;

            context.Entry(clienteJuridicoDB.Cliente).State = EntityState.Modified;
            context.Entry(clienteJuridicoDB).State = EntityState.Modified;
            context.SaveChanges();
        }
    }
}
